from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from datetime import date
import datetime
from apps.goods.models import GoodsVisitCount
from apps.meiduo_admin.serializers.statistical import GoodsVisitCountSerializer

from apps.orders.models import OrderInfo
from apps.users.models import User


# 日增用户
class UserTotalCountView(APIView):
    # 设置视图权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        today = date.today()
        count = User.objects.all().count()
        return Response({
            "count": count,
            "date": today
        })


# 日下单用户数量
class UserDailyOrderCountView(APIView):
    def get(self, request):
        today = date.today()
        count = User.objects.filter(orderinfo__create_time__gte=today).count()
        return Response({
            "count": count,
            "date": today
        })


# 日活用户
class UserDailyAddView(APIView):
    # 设置视图权限
    permission_classes = [IsAuthenticated]

    def get(self, request):
        today = date.today()
        count = User.objects.filter(date_joined__gte=today).count()
        return Response({
            "count": count,
            "date": today
        })


# 月增用户
class UserMonthCountView(APIView):
    def get(self, request):
        # 获取30天前的日期
        month_start_day = date.today() - datetime.timedelta(days=30)
        data = []
        # 遍历30天
        for i in range(30):
            start_day = month_start_day + datetime.timedelta(days=i)
            end_day = month_start_day + datetime.timedelta(days=i+1)
            count = User.objects.filter(date_joined__gte=start_day, date_joined__lte=end_day).count()
            data.append({
                "date": start_day,
                "count": count
            })
        return Response(data)


# 日分类商品数量统计
class UserCategoryCountAPIView(APIView):
    def get(self, request):
        # 获取当日时间
        today = date.today()
        # 查询当日分类商品访问记录表
        gvsc = GoodsVisitCount.objects.filter(date=today)

        # 序化器序化对象
        s = GoodsVisitCountSerializer(instance=gvsc, many=True)
        # 返回序化数据
        return Response(s.data)

